package com.shuigu.aop;

import com.alibaba.fastjson2.JSONObject;
import com.shuigu.mapper.UmsSysLogMapper;
import com.shuigu.pojo.entity.UmsSysLog;
import com.shuigu.utils.NetUtils;
import com.shuigu.utils.UserContext;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Slf4j
@Component
public class LogAspect {
    @Resource
    private UmsSysLogMapper umsSysLogMapper;

    @Resource
    private HttpServletRequest httpServletRequest;

    @Around("@annotation(com.shuigu.anno.Log)")
    public Object recordLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        log.info("日志记录开始============================》");


//        // 获取被增强类和方法的信息
//        Signature signature = proceedingJoinPoint.getSignature();
//        MethodSignature methodSignature =  (MethodSignature) signature;
//        // 获取被增强的方法对象
//        Method method = methodSignature.getMethod();
//        // 从方法中解析注解
//        if(method != null){
//            Log logAnnotation = method.getAnnotation(Log.class);
//            System.out.println(logAnnotation.name());
//        }
//        // 方法名
//        String name = method.getName();
//        // 访问uri
//        String uri = httpServletRequest.getRequestURI();
//        // 请求方式
//        String method = httpServletRequest.getMethod();

        //操作类名
        String className = proceedingJoinPoint.getTarget().getClass().getName();

        //操作方法名
        String methodName = proceedingJoinPoint.getSignature().getName();

        //操作方法参数
        Object[] args = proceedingJoinPoint.getArgs();
        String methodParams = Arrays.toString(args);

        long begin = System.currentTimeMillis();

        // 调用原始目标方法运行(先执行目标原始方法)
        Object result = proceedingJoinPoint.proceed();

        long end = System.currentTimeMillis();

        // 登录成功后的操作，日志记录
        String operateUser = UserContext.getUsername();
        LocalDateTime operateTime = LocalDateTime.now();
        String ipAddress = NetUtils.getIpAddress(httpServletRequest);
        log.info("获取客户端ip================>{}", ipAddress);

        //方法返回值
        String returnValue = JSONObject.toJSONString(result);

        //操作耗时
        long costTime = end - begin;

        //记录操作日志
        UmsSysLog operateLog = new UmsSysLog(null, operateUser, operateTime, ipAddress,costTime);
        umsSysLogMapper.insert(operateLog);

        return  result;
    }
}
